/**
* Copyright (c) 2016-2100 yunclouds
*/
package com.yunqian.redot.service;

import com.yunqian.redot.constant.BusinessType;
import com.yunqian.redot.constant.Operation;
import com.yunqian.redot.constant.OperationMenus;
import com.yunqian.redot.constant.ShowStatus;
import com.yunqian.redot.domain.Contents;
import com.yunqian.redot.domain.Information;
import com.yunqian.redot.domain.dto.InformationDto;
import com.yunqian.redot.repository.ContentsRepository;
import com.yunqian.redot.repository.InformationRepository;
import com.yunqian.service.BaseService;
import com.yunqian.util.bean.BeanUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 咨询文章
 *
 * @author zsy
 * 2018-09-29 15:54:34
 */
@Service
@Log4j2
public class InformationService extends BaseService<Information, Long> {

    @Autowired
    private InformationRepository informationRepository;
    @Autowired
    private ContentsRepository contentsRepository;
    @Autowired
    private OperationLogService operationLogService;

    public void save(InformationDto dto, Long userId) {
        Information information = dto.getInformation();
        super.save(information);
        super.update(information);
        List<Contents> contentsList = dto.getContentsList();
        contentsList.forEach(item -> {
            item.setRelateBusiness(BusinessType.INFORMATION.getCode());
            item.setRelateId(information.getId());
            item.setSaveTime(new Date());
        });
        contentsRepository.saveAll(contentsList);
        operationLogService.save(OperationMenus.NEWS_LIST, Operation.ADD, userId);
    }

    public void update(InformationDto dto, Long userId) {
        Information information = dto.getInformation();
        Information origInformation = this.getById(information.getId());
        BeanUtil.copyNotNullProperties(origInformation, information);
        super.update(origInformation);
        // 删除原先的数据
        contentsRepository.deleteByRelateBusinessAndRelateId(BusinessType.INFORMATION.getCode(), information.getId());
        // 新增
        List<Contents> contents = dto.getContentsList();
        contents.forEach(item -> {
            item.setRelateBusiness(BusinessType.INFORMATION.getCode());
            item.setRelateId(information.getId());
            item.setSaveTime(new Date());
        });
        contentsRepository.saveAll(contents);
        operationLogService.save(OperationMenus.NEWS_LIST, Operation.UPDATE, userId);
    }

    public List<Information> getAllByStatus(){
        return informationRepository.findAllByStatus(ShowStatus.YES.getCode());
    }
}
